package com.gene.controller.file;

import com.aliyun.oss.OSSClient;
import com.gene.utils.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/gene-safe")
public class UsersUpload {

    /**
     * 用户的图片上传
     *
     * @return
     */
    @RequestMapping(value = "/users/Upload", method = RequestMethod.POST)
    @ResponseBody
    public ResultData itemUpload(@RequestParam(value = "file", required = false) MultipartFile[] file) throws Exception {
        ResultData result = new ResultData();
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        String files="";
        try {
            for (MultipartFile mult : file) {
                String originalImageName = mult.getOriginalFilename();
                String suffix = originalImageName.substring(originalImageName.lastIndexOf(".") + 1);
                String imageName = ImageUtil.getImageName(GenerationIdUtils.generateShortUuid(), suffix);
                String folder = AliyunOSSClientUtil.createCurrentFolder(ossClient, OSSClientConstants.BACKET_NAME, OSSClientConstants.USERS);
                AliyunOSSClientUtil.createObject(ossClient, OSSClientConstants.BACKET_NAME, folder + imageName, mult.getInputStream());
                files+=folder+imageName+",";
            }
            ossClient.shutdown();
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.SUCCESS);
            result.setData(new StringBuffer(files).deleteCharAt(files.length()-1));//图片路径
            return result;
        } catch (Exception e) {
            ossClient.shutdown();
            throw new RuntimeException("服务器繁忙，上传图片失败");
        }
    }
}
